<template>
  <div>
    <el-dialog :center="true" :title="title" :visible.sync="formVisible" width="60%" :close-on-click-modal="closeModel" :close-on-press-escape="closeModel" :before-close="() => {$emit('update:formVisible', false),$refs['ruleForm'].resetFields(),repeat = [],(empty = []);}" @open="open">
      <div class="from_box">
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="140px" class="demo-ruleForm">
          <el-form-item label="请选择文件" prop="checkedFiled">
            <el-upload ref="upload" class="upload-demo" :action="urlUpload + url" :headers="headers" :on-remove="handleRemove" :on-success="handleSuccess" :on-error="handleError" :on-change="handleChange" :file-list="list" :auto-upload="false" :multiple="false" :before-upload="handleBeforeUpload">
              <el-button slot="trigger" size="small" type="primary">选取Excel文件
              </el-button>
              <span style="margin-left: 30px;" class="down_box">
                <i class="el-icon-download" />
                <span v-if="template" @click="downTemplateClick">导入模板下载</span>
                <span v-else @click="download">导入模板下载</span>
              </span>
            </el-upload>
          </el-form-item>
          <el-form-item v-if="repeat.length > 0 || empty.length > 0">
            <el-button v-if="repeat.length > 0" size="mini" type="success" @click="copy($event ,repeat)">copy重复</el-button>
            <el-button v-if="empty.length > 0" size="mini" type="success" @click="copy($event, empty)">copy未匹配</el-button>
          </el-form-item>
          <el-form-item v-if="repeat.length > 0 || empty.length > 0" label="未上传成功运单集合">
            <div v-if="repeat.length > 0">重复上传运单号({{ repeat.length }})：
              <span v-for="(item, index) in repeat" :key="item+'repeat'"><i v-if="index > 0">，</i>{{ item }}</span>
            </div>
            <div v-if="empty.length > 0">未匹配上运单号({{ empty.length }})：
              <span v-for="(item, index) in empty" :key="item+'empty'"><i v-if="index > 0">，</i>{{ item }}</span>
            </div>
          </el-form-item>
        </el-form>
        <div style="text-align: center;">
          <el-button type="primary" :disabled="list.length > 0 ? false : true" :loading="isbtn" @click="submitForm('ruleForm')">保存
          </el-button>
          <el-button @click="handleCancel">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { downTemplate } from '@/utils/index.js'
import Clipboard from 'clipboard'
export default {
  props: {
    template: {
      type: String,
      default: ''
    },
    url: {
      type: String,
      default: ''
    },
    formVisible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '导入'
    },
    duration: {
      type: String,
      default: '4500'
    },
    closeModel: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      fileList: [],
      urlUpload: process.env.VUE_APP_BASE_API,
      headers: {
        Accept: 'application/json',
        authorization: 'Bearer ' + getToken()
      },
      checkAll: false,
      checkedFiled: [],
      isIndeterminate: true,
      ruleForm: {
        file: ''
      },
      isbtn: false,
      rules: {
        checkedFiled: [
          { required: true, message: '请选择至少一个字段', trigger: 'blur' }
        ]
      },
      repeat: [],
      empty: [],
      list: []
    }
  },
  methods: {
    // F复制运单号
    copy(e, text) {
      const textNew = text.join('\n')
      const clipboard = new Clipboard(e.target, { text: () => textNew })
      clipboard.on('success', e => {
        this.$message({ type: 'success', message: '复制成功' })
        // 释放内存
        clipboard.off('error')
        clipboard.off('success')
        clipboard.destroy()
      })
      clipboard.on('error', e => {
        // 不支持复制
        this.$message({ type: 'waning', message: '该浏览器不支持自动复制' })
        // 释放内存
        clipboard.off('error')
        clipboard.off('success')
        clipboard.destroy()
      })
    },
    open() {
      this.repeat = []
      this.empty = []
    },
    handleChange(file, fileList) {
      this.list = fileList
    },
    downTemplateClick() {
      window.location.href = downTemplate(this.template)
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
      this.list = fileList
    },
    // 下载
    download() {
      const vm = this
      vm.$emit('download')
    },
    // 上传成功
    handleSuccess(file) {
      const vm = this
      if (file.message === 'success') {
        vm.$message.success('导入成功')
        vm.repeat = file.data.repeat || []
        vm.empty = file.data.empty || []
        vm.handleImportSuccess(file.data)
        vm.$emit('handleRefresh')
        vm.isbtn = false
        // 清空上传列表
        vm.$refs.upload.clearFiles()
        if (this.url !== '/logisticsTransportOrders/importOrder') {
          vm.$emit('update:formVisible', false)
        }

        // vm.$emit('update:formVisible', false)
      } else {
        vm.$refs.upload.clearFiles()
        vm.$message.error(file.message)
        vm.isbtn = false
      }
    },

    //  handleImportSuccess
    handleImportSuccess(res) {
      console.log('123111111111111111')
      const urls = ['/productPlatformSkus/importSku', '/zipImport', '/logisticsTransportOrders/importOrder',
        '/deliveryOrders/importLogisticsOrderNo', '/deliveryOrders/importLogisticsOrder', '/combinationPlatformSkus/importSku',
        '/orderRecords/importCustomerOrder', '/orderRecords/importBorrowSellOrder', '/part/importPart', '/products/developImprot']
      if (urls.includes(this.url)) {
        console.log('123111111111112222')
        // 成功数量
        const successNumber = res.success ? res.success.length : 0
        // 重复数量
        const repeatNumber = res.repeat ? res.repeat.length : 0
        // 品配失败数量
        const emptyNumber = res.empty ? res.empty.length : 0
        this.$notify.info({
          title: '导入结果',
          message: `导入成功${successNumber}个，重复数量${repeatNumber}个，匹配失败数量${emptyNumber}个`,
          duration: this.duration === '0' ? 0 : 4500
        })
      }
    },
    // 上传失败
    handleError(file) {
      const vm = this
      vm.$message.error('上传失败')
      vm.isbtn = false
      vm.repeat = file.data.repeat || []
      vm.empty = file.data.empty || []
      vm.$refs.upload.clearFiles()
    },
    // 关闭
    handleCancel() {
      this.list = []
      this.isbtn = false
      this.$emit('update:formVisible', false)
    },
    handleBeforeUpload(file) {
      const typeList = ['xls', 'xlsx']
      const errMsg = '请上传excel文件'
      return this.beforeUpload(file, typeList, errMsg)
    },
    beforeUpload(file, arr = [], mssage) {
      const typeList = [...arr]
      const fileName = file.name
      const extension = fileName.substr(fileName.lastIndexOf('.') + 1)
      const isRT = typeList.includes(extension)
      if (!isRT) {
        this.$message.error(mssage)
      }
      return isRT
    },
    submitForm(formName) {
      this.isbtn = true
      this.$refs.upload.submit()
    }
  }
}
</script>

<style lang="scss" scoped>
.down_box {
  cursor: pointer;
}
</style>
